package net.ys.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.ys.util.req.HttpResponse;
import net.ys.util.req.HttpsUtil;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: NMY
 * @Date: 2021/11/3
 * @Time: 16:52
 */
@Service
public class ApiService {

    /**
     * 获取项目id
     *
     * @param prjName
     * @return
     */
    public String getPrjId(String prjName) {
        HttpResponse response = HttpsUtil.doGet("https://images-docker.zhulong.com.cn/api/projects?name=" + prjName + "&public=false&owner=admin&page=1&page_size=100");
        String value = response.getValue();
        JSONObject o = JSONArray.parseArray(value).getJSONObject(0);
        String projectId = o.getString("project_id");
        return projectId;
    }

    public List<String> getRepositories(String prjId) {
        HttpResponse response = HttpsUtil.doGet("https://images-docker.zhulong.com.cn/api/repositories?project_id=" + prjId + "&page=1&page_size=100");
        String value = response.getValue();
        JSONArray objects = JSONArray.parseArray(value);
        List<String> images = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            images.add(objects.getJSONObject(i).getString("name"));
        }
        return images;
    }

    public List<String> getTags(String imageName) throws UnsupportedEncodingException {
        String name = URLEncoder.encode(imageName, "UTF-8");
        HttpResponse response = HttpsUtil.doGet("https://images-docker.zhulong.com.cn/api/repositories/" + name + "/tags");
        String value = response.getValue();
        JSONArray objects = JSONArray.parseArray(value);
        List<String> tags = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            tags.add(objects.getJSONObject(i).getString("name"));
        }
        return tags;
    }
}
